package it.tukano.swingdeco.text;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class SizedDigitsDocument extends PlainDocument {

    private static final long serialVersionUID = 0;
    private int size = Integer.MAX_VALUE;

    public SizedDigitsDocument(int maxCharCount) {
        size = maxCharCount;
    }

    @Override
    public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
        str = str.replaceAll("\\D", "");
        int space = Math.min(size - getLength(), str.length());
        if(space > 0) {
            super.insertString(offs, str, a);
        }
    }

    @Override
    public void replace(int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
        remove(offset, length);
        if(text != null) insertString(offset, text, attrs);
    }
}
